﻿using AutoMapper;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfance;
using B.S.BasicData.Write.Application.Common.Menu;
using MediatR;
using System.Transactions;

namespace B.S.BasicData.Write.Application.Handler.Menu
{
    public class MenuAddCommandHandle:IRequestHandler<MenuAddCommand, ApiResult<MenuModel>>
    {
        private readonly IBaseRepository<MenuModel> MenuDal;
        private readonly IMapper mapper;


        public MenuAddCommandHandle(IBaseRepository<MenuModel> menuDal, IMapper mapper)
        {
            MenuDal = menuDal;
            this.mapper = mapper;
        }

        public Task<ApiResult<MenuModel>> Handle(MenuAddCommand request, CancellationToken cancellationToken)
        {
            ApiResult<MenuModel> result = new ApiResult<MenuModel>();

            var menuname = MenuDal.GetAll().Where(x=>x.MenuName == request.MenuName && x.IsDeleted == false && x.ParentId == request.ParentId).FirstOrDefault();
            if (menuname != null)
            {
                result.Code = ApiEnum.Error;
                result.Message = "同一级菜单中该名称已存在";
                return Task.FromResult(result);
            }
            var model = mapper.Map<MenuModel>(request);
            if (model.ParentId == null)
            {
                model.ParentId = 0;
            }

            MenuModel menu = new MenuModel();
            menu.MenuId = request.MenuId;
            menu.MenuName = request.MenuName;
            menu.ParentId = request.ParentId ?? 0;
            menu.MenuUrl = request.MenuUrl;
            menu.CreateBy = request.CreateBy;
            menu.CreateDate = request.CreateDate;

            MenuDal.Add(menu);
            result.Code = ApiEnum.Success;
            result.Message = ApiEnum.Success.ToString();
            result.Data = menu;
            return Task.FromResult(result);


            //var model = mapper.Map<MenuModel>(request);
            //var model = mapper.Map<MenuModel>(request);
            //var r = 0;
            //using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            //{
            //    r = MenuDal.Add(model).Result;
            //    tran.Complete();
            //}
            //if (r > 0)
            //{
            //    result.Code = ApiEnum.Success;
            //    result.Message = "添加成功";
            //    return Task.FromResult(result);
            //}
            //else
            //{
            //    result.Code = ApiEnum.Error;
            //    result.Message = "添加失败";
            //    return Task.FromResult(result);
            //}



        }


         

    }
}
